package com.kingre.et.dao.jpa;

import java.util.List;

import com.kingre.et.dao.IIPDAO;
import com.kingre.et.model.IP;
import com.kingre.et.model.School;

public class IPDAOJPA extends GenericDAOJPA<IP, Integer> implements IIPDAO {

    @SuppressWarnings("unchecked")
    public List<IP> findByName(String name) {
        String hql;
        if(name == null || name.equals("")){
            hql = "FROM IP ORDER BY school.id, id ";
        }
        else{
            String[] arr = org.apache.commons.lang.StringUtils.split(name, ".");
            Long ip = Integer.parseInt(arr[0]) * 1000000000L
                        + Integer.parseInt(arr[1]) * 1000000L
                        + Integer.parseInt(arr[2]) * 1000L
                        + Integer.parseInt(arr[3]);
          hql = "FROM IP WHERE " + ip + " >= fromIP and " + ip + " <= endIP ORDER BY school.id, id ";
        }
        return this.getJpaTemplate().find(hql);
    }

    @SuppressWarnings("unchecked")
    public List<IP> findBySchoolAndName(School school, String name) {
        String hql;
        if(name == null || name.equals("")){
            hql = "FROM IP WHERE school = ? ORDER BY school.id, id ";
        }
        else{
            String[] arr = org.apache.commons.lang.StringUtils.split(name, ".");
            Long ip = Integer.parseInt(arr[0]) * 1000000000L
                        + Integer.parseInt(arr[1]) * 1000000L
                        + Integer.parseInt(arr[2]) * 1000L
                        + Integer.parseInt(arr[3]);
            hql = "FROM IP WHERE school = ? AND " + ip + " >= fromIP and " + ip + " <= endIP ORDER BY school.id, id ";
        }
        return this.getJpaTemplate().find(hql, school);
    }

}
